package com.itheima.bos.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.system.RoleRepository;
import com.itheima.bos.domain.system.Menu;
import com.itheima.bos.domain.system.Permission;
import com.itheima.bos.domain.system.Role;
import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleRepository roleRepository;
	@Override
	public List<Role> findByUser(User user) {
		//基于用户查询角色
		if (user.getUsername().equals("admin")) {
			return roleRepository.findAll();
		} else {
			return roleRepository.findByUser(user.getId());
		}
	}
	@Override
	public List<Role> findAll() {
		
		return roleRepository.findAll();
	}
	@Override
	public void saveRole(Role role, String[] permissionIds, String menuIds) {
			roleRepository.save(role);
			if (permissionIds != null) {
				for (String permissionId : permissionIds) {
					Permission permission = new Permission();
					permission.setId(Integer.parseInt(permissionId));
					role.getPermissions().add(permission);
				}
			}
			if (StringUtils.isNoneBlank(menuIds)) {
				String[] menuIdArray = menuIds.split(",");
				for (String menuId : menuIdArray) {
					Menu menu = new Menu();
					menu.setId(Integer.parseInt(menuId));
					role.getMenus().add(menu);
				}
			}
			
	}

}
